<template>
  <view class="container">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-state">
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 订单详情内容 -->
    <view v-else-if="orderDetail" class="order-detail">
      <!-- 订单状态卡片 -->
      <view class="status-card">
        <view class="status-info">
          <text class="status-text" :class="getStatusClass(orderDetail.status)">
            {{ getStatusText(orderDetail.status) }}
          </text>
          <text class="order-number">订单号：{{ orderDetail.order_number }}</text>
        </view>
      </view>

      <!-- 超时提醒 -->
      <view v-if="showOvertimeReminder" class="overtime-reminder">
        <text class="reminder-text">⚠️ 已经超过入场时间请去我的页面联系客服取消</text>
      </view>

      <!-- 停车场信息 -->
      <view class="info-card">
        <view class="card-header">
          <text class="card-title">停车场信息</text>
        </view>
        <view class="card-content">
          <view class="info-row">
            <text class="info-label">停车场名称</text>
            <text class="info-value">{{ orderDetail.parking_lot.name }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">停车场地址</text>
            <text class="info-value address-text" @longpress="copyAddress">
              {{ orderDetail.parking_lot.address }}
            </text>
            <text class="copy-tip">长按复制地址</text>
          </view>
          <view class="info-row" v-if="orderDetail.parking_lot.contact_phone">
            <text class="info-label">联系电话</text>
            <text class="info-value phone-text" @click="callPhone(orderDetail.parking_lot.contact_phone)">
              {{ orderDetail.parking_lot.contact_phone }}
            </text>
          </view>
          <view class="info-row" v-if="orderDetail.parking_lot.backup_phone">
            <text class="info-label">备用电话</text>
            <text class="info-value phone-text" @click="callPhone(orderDetail.parking_lot.backup_phone)">
              {{ orderDetail.parking_lot.backup_phone }}
            </text>
          </view>
        </view>
      </view>

      <!-- 订单信息 -->
      <view class="info-card">
        <view class="card-header">
          <text class="card-title">订单信息</text>
        </view>
        <view class="card-content">
          <view class="info-row">
            <text class="info-label">车牌号码</text>
            <text class="info-value">{{ orderDetail.license_plate }}</text>
          </view>
          <view class="info-row" v-if="orderDetail.contact_phone">
            <text class="info-label">联系手机号</text>
            <text class="info-value phone-text" @click="callPhone(orderDetail.contact_phone)">
              {{ orderDetail.contact_phone }}
            </text>
          </view>
          <view class="info-row">
            <text class="info-label">停车类型</text>
            <text class="info-value parking-type" :class="orderDetail.parking_type">
              {{ orderDetail.parking_type === "outdoor" ? "🌤️ 室外停车" : "🏠 室内停车" }}
            </text>
          </view>
          <view class="info-row">
            <text class="info-label">预计入场</text>
            <text class="info-value">{{ formatDateTime(orderDetail.planned_start_time) }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">预计离场</text>
            <text class="info-value">{{ formatDateTime(orderDetail.planned_end_time) }}</text>
          </view>
          <view class="info-row" v-if="orderDetail.actual_start_time">
            <text class="info-label">实际入场</text>
            <text class="info-value">{{ formatDateTime(orderDetail.actual_start_time) }}</text>
          </view>
          <view class="info-row" v-if="orderDetail.actual_end_time">
            <text class="info-label">实际离场</text>
            <text class="info-value">{{ formatDateTime(orderDetail.actual_end_time) }}</text>
          </view>
        </view>
      </view>

      <!-- 费用明细 -->
      <view class="info-card">
        <view class="card-header">
          <text class="card-title">费用明细</text>
        </view>
        <view class="card-content">
          <view class="info-row" v-if="orderDetail.duration_days">
            <text class="info-label">停车天数</text>
            <text class="info-value">{{ orderDetail.duration_days }} 天</text>
          </view>
          <view class="info-row">
            <text class="info-label">停车费用</text>
            <text class="info-value">¥{{ orderDetail.total_amount }}</text>
          </view>
          <view class="info-row" v-if="orderDetail.discount_amount > 0">
            <text class="info-label">优惠金额</text>
            <text class="info-value discount-text">-¥{{ orderDetail.discount_amount }}</text>
          </view>
          <view class="info-row total-row">
            <text class="info-label">实付金额</text>
            <text class="info-value total-price">¥{{ orderDetail.final_amount }}</text>
          </view>
          <view class="info-row" v-if="orderDetail.price_description">
            <text class="info-label">计费说明</text>
            <text class="info-value description-text">{{ orderDetail.price_description }}</text>
          </view>
        </view>
      </view>

      <!-- 优惠券信息 -->
      <view class="info-card" v-if="orderDetail.coupon_info">
        <view class="card-header">
          <text class="card-title">优惠券信息</text>
        </view>
        <view class="card-content">
          <view class="info-row">
            <text class="info-label">优惠券名称</text>
            <text class="info-value">{{ orderDetail.coupon_info.name }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">优惠金额</text>
            <text class="info-value discount-text">-¥{{ orderDetail.coupon_info.discount_amount }}</text>
          </view>
        </view>
      </view>

      <!-- 支付信息 -->
      <view class="info-card" v-if="orderDetail.paid_at">
        <view class="card-header">
          <text class="card-title">支付信息</text>
        </view>
        <view class="card-content">
          <view class="info-row">
            <text class="info-label">支付时间</text>
            <text class="info-value">{{ formatDateTime(orderDetail.paid_at) }}</text>
          </view>
          <view class="info-row" v-if="orderDetail.payment_method">
            <text class="info-label">支付方式</text>
            <text class="info-value">{{ getPaymentMethodText(orderDetail.payment_method) }}</text>
          </view>
          <view class="info-row" v-if="orderDetail.transaction_id">
            <text class="info-label">交易号</text>
            <text class="info-value">{{ orderDetail.transaction_id }}</text>
          </view>
        </view>

        <!-- 补款记录（显示 additional_payments 简要进度） -->
        <view class="info-card" v-if="parsedPayment?.additional_payments?.length">
          <view class="card-header">
            <text class="card-title">补款记录</text>
          </view>
          <view class="card-content">
            <view class="info-row" v-for="p in parsedPayment.additional_payments" :key="p.out_trade_no">
              <text class="info-label">{{ p.out_trade_no }}</text>
              <text class="info-value">¥{{ p.amount }} - {{ p.status === "SUCCESS" ? "已完成" : "待支付" }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 评价信息 -->
      <view class="info-card" v-if="orderDetail.status === 'completed' && orderDetail.review">
        <view class="card-header">
          <text class="card-title">我的评价</text>
        </view>
        <view class="card-content">
          <view class="review-content">
            <view class="review-rating">
              <view class="rating-stars">
                <text v-for="i in 5" :key="i" class="star" :class="{ 'star-filled': i <= orderDetail.review.rating }"> ★ </text>
              </view>
              <text class="rating-text">{{ orderDetail.review.rating }}.0分</text>
            </view>
            <view class="review-comment" v-if="orderDetail.review.comment">
              <text class="comment-text">{{ orderDetail.review.comment }}</text>
            </view>
            <view class="review-time">
              <text class="time-text">评价时间：{{ formatDateTime(orderDetail.review.created_at) }}</text>
            </view>

            <!-- 管理员回复 -->
            <view class="admin-reply" v-if="orderDetail.review.replies && orderDetail.review.replies.length > 0">
              <view v-for="reply in orderDetail.review.replies" :key="reply.id" class="reply-item">
                <view class="reply-header">
                  <text class="reply-author">{{ reply.reply_user_nickname || "管理员" }}回复：</text>
                  <text class="reply-time">{{ formatDateTime(reply.created_at) }}</text>
                </view>
                <text class="reply-content">{{ reply.content }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-buttons" v-if="showActionButtons">
        <!-- 待支付：取消 / 立即支付 -->
        <button v-if="orderDetail.status === 'pending_payment'" class="action-btn cancel-btn" @click="cancelOrder">取消订单</button>
        <button v-if="orderDetail.status === 'pending_payment'" class="action-btn pay-btn" @click="payOrder">立即支付</button>

        <!-- 进行中且还没实际入场且没超时：可以取消订单 -->
        <button v-if="orderDetail.status === 'in_progress' && !orderDetail.actual_start_time && !showOvertimeReminder" 
                class="action-btn cancel-btn" @click="cancelOrder">
          取消订单
        </button>

        <!-- 进行中：延后离场（不管是否入场都可以延后） -->
        <button v-if="orderDetail.status === 'in_progress'" class="action-btn pay-btn" @click="quickLateDeparture">延后离场</button>

        <!-- 待补款：支付尾款 -->
        <button v-if="orderDetail.status === 'pending_additional_payment'" class="action-btn pay-btn" @click="payAdditional">
          支付尾款
        </button>

        <!-- 已完成：评价 -->
        <button v-if="orderDetail.status === 'completed' && !orderDetail.review" class="action-btn review-btn" @click="showReviewDialog">
          评价服务
        </button>
      </view>
    </view>

    <!-- 错误状态 -->
    <view v-else class="error-state">
      <text class="error-text">{{ errorMessage || "订单不存在或加载失败" }}</text>
      <button class="retry-btn" @click="loadOrderDetail">重新加载</button>
    </view>

    <!-- 评价对话框 -->
    <view class="review-modal" v-if="showReviewModal" @click="hideReviewDialog">
      <view class="review-dialog" @click.stop>
        <view class="dialog-header">
          <text class="dialog-title">评价服务</text>
          <text class="close-btn" @click="hideReviewDialog">×</text>
        </view>

        <view class="dialog-content">
          <view class="parking-info">
            <text class="parking-name">{{ orderDetail?.parking_lot?.name }}</text>
          </view>

          <view class="rating-section">
            <text class="section-title">服务评分</text>
            <view class="rating-stars">
              <text v-for="i in 5" :key="i" class="star clickable" :class="{ 'star-filled': i <= reviewForm.rating }" @click="setRating(i)">
                ★
              </text>
            </view>
            <text class="rating-desc">{{ getRatingDesc(reviewForm.rating) }}</text>
          </view>

          <view class="comment-section">
            <text class="section-title">评价内容（可选）</text>
            <textarea
              class="comment-input"
              v-model="reviewForm.comment"
              placeholder="请分享您的停车体验..."
              maxlength="200"
              :show-confirm-bar="false"
            />
            <text class="char-count">{{ reviewForm.comment.length }}/200</text>
          </view>
        </view>

        <view class="dialog-footer">
          <button class="dialog-btn cancel-btn" @click="hideReviewDialog">取消</button>

          <button class="dialog-btn submit-btn" :disabled="reviewForm.rating === 0 || submittingReview" @click="submitReview">
            {{ submittingReview ? "提交中..." : "提交评价" }}
          </button>
        </view>
      </view>
    </view>

    <!-- 延后离场时间选择模态框 -->
    <view class="time-picker-modal" v-if="showTimePickerModal" @click="hideTimePicker">
      <view class="time-picker-dialog" @click.stop>
        <view class="dialog-header">
          <text class="dialog-title">选择新的离场时间</text>
          <text class="close-btn" @click="hideTimePicker">×</text>
        </view>

        <view class="dialog-content">
          <view class="current-time-info">
            <text class="info-text">当前预计离场：{{ formatDateTime(orderDetail?.planned_end_time) }}</text>
          </view>

          <view class="time-selector">
            <view class="time-item">
              <text class="time-label">新离场日期</text>
              <picker mode="date" :value="newExitDate" @change="onNewExitDateChange">
                <view class="datetime-value">
                  {{ newExitDate || "选择日期" }}
                </view>
              </picker>
            </view>

            <view class="time-item">
              <text class="time-label">新离场时间</text>
              <picker mode="time" :value="newExitTime" @change="onNewExitTimeChange">
                <view class="datetime-value">
                  {{ newExitTime || "选择时间" }}
                </view>
              </picker>
            </view>
          </view>
        </view>

        <view class="dialog-footer">
          <button class="dialog-btn cancel-btn" @click="hideTimePicker">取消</button>
          <button class="dialog-btn confirm-btn" @click="confirmNewExitTime">确认延后</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue"
import { getUserOrderById, submitOrderReview } from "../../api/user.js"
import { cancelParkingOrder } from "../../api/parking.js"
import { initiatePayment, getUserOpenid, invokePaymentParams } from "../../utils/payment.js"
import { post } from "../../utils/request.js"


// 响应式数据
const orderDetail = ref<any>(null)
const loading = ref<boolean>(false)
const errorMessage = ref<string>("")
const orderId = ref<number>(0)

// 评价相关数据
const showReviewModal = ref<boolean>(false)
const submittingReview = ref<boolean>(false)
const reviewForm = ref({
  rating: 0,
  comment: "",
})

// 延后离场时间选择相关数据
const showTimePickerModal = ref<boolean>(false)
const newExitDate = ref<string>("")
const newExitTime = ref<string>("")

// 计算属性
const showActionButtons = computed(() => {
  if (!orderDetail.value) return false
  return (
    ["pending_payment", "in_progress", "pending_additional_payment"].includes(orderDetail.value.status) ||
    (orderDetail.value.status === "completed" && !orderDetail.value.review)
  )
})

// 判断是否在预计停车时间前（当前时间小于预计入场时间）
const isBeforePlannedStart = computed(() => {
  if (!orderDetail.value?.planned_start_time) return false
  return new Date() < new Date(orderDetail.value.planned_start_time)
})

// 判断是否显示超时提醒（已支付但超过预计入场时间且还没实际入场）
const showOvertimeReminder = computed(() => {
  if (!orderDetail.value?.planned_start_time) return false
  // 必须是已支付的订单（进行中状态或待补款状态）
  if (!['in_progress', 'pending_additional_payment'].includes(orderDetail.value.status)) return false
  // 必须还没有实际入场时间（说明还没真正入场）
  if (orderDetail.value.actual_start_time) return false
  // 当前时间超过预计入场时间
  return new Date() >= new Date(orderDetail.value.planned_start_time)
})

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending_payment: "待支付",
    in_progress: "进行中",

    pending_additional_payment: "待补款",
    completed: "已完成",
    cancelled: "已取消",
  }
  return statusMap[status] || status
}

// 获取状态样式类
const getStatusClass = (status: string) => {
  const classMap: Record<string, string> = {
    pending_payment: "status-pending",
    in_progress: "status-progress",
    pending_additional_payment: "status-pending",
    completed: "status-completed",
    cancelled: "status-cancelled",
  }
  return classMap[status] || ""
}

// 获取支付方式文本
const getPaymentMethodText = (method: string) => {
  if (!method) return "未知"

  // 如果是简单的字符串
  if (typeof method === 'string' && !method.startsWith('{')) {
    const methodMap: Record<string, string> = {
      mock_payment: "模拟支付",
      wechat_pay: "微信支付",
      alipay: "支付宝",
    }
    return methodMap[method] || method
  }

  // 如果是 JSON 格式（包含尾款信息）
  try {
    const parsed = JSON.parse(method)
    if (parsed.additional_payments && Array.isArray(parsed.additional_payments)) {
      const successCount = parsed.additional_payments.filter((p: any) => p.status === 'SUCCESS').length
      const totalCount = parsed.additional_payments.length
      return `微信支付 (含${totalCount}笔尾款)`
    }
    return "微信支付"
  } catch (error) {
    return "微信支付"
  }
}

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
  if (!dateTimeStr) return ""
  const date = new Date(dateTimeStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, "0")
  const day = String(date.getDate()).padStart(2, "0")
  const hours = String(date.getHours()).padStart(2, "0")
  const minutes = String(date.getMinutes()).padStart(2, "0")
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 复制地址到剪贴板
const copyAddress = () => {
  if (!orderDetail.value?.parking_lot?.address) return

  uni.setClipboardData({
    data: orderDetail.value.parking_lot.address,
    success: () => {
      uni.showToast({
        title: "地址已复制",
        icon: "success",
      })
    },
    fail: () => {
      uni.showToast({
        title: "复制失败",
        icon: "none",
      })
    },
  })
}

// 拨打电话
// 解析支付方法 JSON 以显示补款进度（放在脚本块末尾，独立定义）
const parsedPayment = computed(() => {
  try {
    return orderDetail.value?.payment_method ? JSON.parse(orderDetail.value.payment_method) : {}
  } catch (e) {
    return {}
  }
})

const callPhone = (phoneNumber: string) => {
  uni.showModal({
    title: "拨打电话",
    content: `确定要拨打 ${phoneNumber} 吗？`,
    success: (res) => {
      if (res.confirm) {
        uni.makePhoneCall({
          phoneNumber: phoneNumber,
          fail: () => {
            uni.showToast({
              title: "拨号失败",
              icon: "none",
            })
          },
        })
      }
    },
  })
}

// 支付订单
const payOrder = () => {
  uni.showModal({
    title: "支付确认",
    content: `确认支付 ¥${orderDetail.value.final_amount} 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({
            title: "支付准备中...",
            mask: true,
          })

          // 获取用户openid
          const openid = await getUserOpenid()

          uni.hideLoading()

          // 发起支付
          const payResult = await initiatePayment({
            orderId: orderDetail.value.id,
            openid: openid,
          })

          if (payResult.success) {
            if (payResult.mock) {
              // 模拟支付成功
              uni.showToast({
                title: "模拟支付成功",
                icon: "success",
              })
            } else {
              // 真实支付成功
              uni.showToast({
                title: "支付成功",
                icon: "success",
              })
            }

            // 重新加载订单详情
            setTimeout(() => {
              loadOrderDetail()
            }, 1500)
          } else if (payResult.cancelled) {
            // 用户取消支付
            uni.showToast({
              title: "支付已取消",
              icon: "none",
            })
          } else {
            // 支付失败
            throw new Error(payResult.message || "支付失败")
          }
        } catch (error) {
          console.error("支付失败:", error)
          uni.showToast({
            title: "支付失败，请重试",
            icon: "none",
          })
        }
      }
    },
  })
}

// 取消订单
const cancelOrder = () => {
  const now = new Date()
  const plannedStartTime = new Date(orderDetail.value.planned_start_time)
  const isBeforeEntry = now < plannedStartTime

  if (isBeforeEntry) {
    // 预计停车时间前 - 允许自动退款
    uni.showModal({
      title: "确认取消",
      content: "预计停车时间前取消将全额原路退回。确定要取消吗？",
      success: async (res) => {
        if (res.confirm) {
          try {
            uni.showLoading({
              title: "取消中...",
              mask: true,
            })

            const response = await cancelParkingOrder(orderDetail.value.id)

            uni.hideLoading()

            if (response.success) {
              uni.showToast({
                title: "订单已取消",
                icon: "success",
              })
              // 重新加载订单详情
              loadOrderDetail()
            } else {
              throw new Error(response.message || "取消订单失败")
            }
          } catch (error) {
            uni.hideLoading()
            console.error("取消订单失败:", error)
            uni.showToast({
              title: "取消订单失败，请重试",
              icon: "none",
            })
          }
        }
      },
    })
  } else {
    // 预计停车时间后 - 提醒联系客服
    uni.showModal({
      title: "联系客服取消",
      content: "您的订单已到预计停车时间，取消订单需要联系客服手动处理退款并扣除相应手续费。",
      showCancel: true,
      cancelText: "我知道了",
      confirmText: "联系客服",
      success: (res) => {
        if (res.confirm) {
          // 显示客服联系方式
          uni.showModal({
            title: "客服联系方式",
            content: "请联系在线客服或拨打客服电话处理取消订单事宜。",
            showCancel: false
          })
        }
      }
    })
  }
}

// 显示评价对话框
const showReviewDialog = () => {
  reviewForm.value = {
    rating: 0,
    comment: "",
  }
  showReviewModal.value = true
}

// 隐藏评价对话框
const hideReviewDialog = () => {
  showReviewModal.value = false
}

// 设置评分
const setRating = (rating: number) => {
  reviewForm.value.rating = rating
}

// 获取评分描述
const getRatingDesc = (rating: number) => {
  const descriptions = ["", "很不满意", "不满意", "一般", "满意", "非常满意"]
  return descriptions[rating] || ""
}

// 提交评价
const submitReview = async () => {
  if (reviewForm.value.rating === 0) {
    uni.showToast({
      title: "请选择评分",
      icon: "none",
    })
    return
  }

  submittingReview.value = true

  try {
    const response = await submitOrderReview(orderDetail.value.id, {
      rating: reviewForm.value.rating,
      comment: reviewForm.value.comment.trim(),
    })

    if (response.success) {
      uni.showToast({
        title: "评价成功",
        icon: "success",
      })

      hideReviewDialog()

      // 重新加载订单详情以显示评价
      setTimeout(() => {
        loadOrderDetail()
      }, 1000)
    } else {
      throw new Error(response.message || "评价失败")
    }
  } catch (error) {
    console.error("提交评价失败:", error)
    uni.showToast({
      title: "评价失败，请重试",
      icon: "none",
    })
  } finally {
    submittingReview.value = false
  }
}

// 加载订单详情
const loadOrderDetail = async () => {
  if (!orderId.value) {
    errorMessage.value = "订单ID无效"
    return
  }

  loading.value = true
  errorMessage.value = ""

  try {
    const response = await getUserOrderById(orderId.value)

    if (response.success) {
      orderDetail.value = response.data
    } else {
      throw new Error(response.message || "获取订单详情失败")
    }
  } catch (error) {
    console.error("获取订单详情失败:", error)
    errorMessage.value = "获取订单详情失败，请重试"
  } finally {
    loading.value = false
  }
}

// 带重试机制的订单刷新（用于支付成功后）
const refreshOrderWithRetry = async (maxRetries = 3, delay = 2000) => {
  let retries = 0
  const originalStatus = orderDetail.value?.status

  while (retries < maxRetries) {
    try {
      await loadOrderDetail()

      // 如果状态已经改变，说明支付回调已处理完成
      if (orderDetail.value?.status !== originalStatus) {
        console.log(`订单状态已更新: ${originalStatus} -> ${orderDetail.value?.status}`)
        return
      }

      // 如果状态没有改变，等待一段时间后重试
      if (retries < maxRetries - 1) {
        console.log(`订单状态未更新，${delay}ms后重试...`)
        await new Promise(resolve => setTimeout(resolve, delay))
      }

      retries++
    } catch (error) {
      console.error(`刷新订单失败 (重试 ${retries + 1}/${maxRetries}):`, error)
      retries++

      if (retries < maxRetries) {
        await new Promise(resolve => setTimeout(resolve, delay))
      }
    }
  }

  console.log('订单刷新重试完成')
}

// 生命周期
onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage.options || {}

  if (options.orderId) {
    orderId.value = parseInt(options.orderId)
    loadOrderDetail()
  } else {
    errorMessage.value = "缺少订单ID参数"
  }
})

// 延后离场 - 显示时间选择器
const quickLateDeparture = () => {
  if (!orderDetail.value) return

  // 获取预计离场时间，设置默认的新离场时间（预计时间+1小时）
  const plannedEndTime = new Date(orderDetail.value.planned_end_time)
  const defaultTime = new Date(plannedEndTime.getTime() + 60 * 60 * 1000)

  // 设置默认值
  newExitDate.value = defaultTime.toISOString().slice(0, 10) // YYYY-MM-DD
  newExitTime.value = defaultTime.toTimeString().slice(0, 5) // HH:MM

  // 显示时间选择器模态框
  showTimePickerModal.value = true
}

// 确认延后离场
const confirmLateDeparture = async (newEndTime) => {
  try {
    uni.showLoading({ title: '计算补款中...' })
    const data = await post(`/api/parking/orders/${orderId.value}/late-departure`, {
      actual_end_time: newEndTime.toISOString()
    })
    if (data.success) {
      if (data.data.additional_amount > 0) {
        uni.showModal({
          title: '延后离场确认',
          content: `新离场时间：${formatDateTime(newEndTime.toISOString())}\n需要补款：¥${data.data.additional_amount}\n是否确认？`,
          success: (res) => {
            if (res.confirm) {
              uni.showToast({ title: '延后离场成功，请支付尾款', icon: 'success' })
              loadOrderDetail()
            }
          }
        })
      } else {
        uni.showToast({ title: data.message || '延后离场成功', icon: 'success' })
        loadOrderDetail()
      }
    } else {
      throw new Error(data.message || '处理失败')
    }
  } catch (err) {
    console.error('延后离场失败:', err)
    uni.showToast({ title: '延后离场失败', icon: 'none' })
  } finally {
    uni.hideLoading()
  }
}

// 支付尾款
const payAdditional = async () => {
  if (!orderDetail.value) return
  try {
    const openid = await getUserOpenid()
    uni.showLoading({ title: "请求中..." })
    const data = await post(`/api/parking/orders/${orderId.value}/additional-pay`, {
      openid
    })
    if (!data.success) throw new Error(data.message || "下单失败")

    const params = data.data.payment_params
    const payRes = await invokePaymentParams(params, orderId.value)
    if (payRes.success) {
      // 支付完成后显示成功提示并刷新订单
      uni.showToast({
        title: '尾款支付成功！',
        icon: 'success',
        duration: 2000
      })
      // 延迟刷新订单，让用户看到成功提示，并增加重试机制
      setTimeout(async () => {
        await refreshOrderWithRetry()
      }, 1500)
    } else {
      // 支付失败或取消
      await loadOrderDetail()
    }
  } catch (err) {
    console.error("支付尾款失败:", err)
    uni.showToast({ title: "支付失败", icon: "none" })
  } finally {
    uni.hideLoading()
  }
}

// 时间选择器相关方法
const hideTimePicker = () => {
  showTimePickerModal.value = false
  newExitDate.value = ""
  newExitTime.value = ""
}

const onNewExitDateChange = (e) => {
  newExitDate.value = e.detail.value
}

const onNewExitTimeChange = (e) => {
  newExitTime.value = e.detail.value
}

const confirmNewExitTime = () => {
  if (!newExitDate.value || !newExitTime.value) {
    uni.showToast({
      title: '请选择完整的日期和时间',
      icon: 'none'
    })
    return
  }

  // 组合日期和时间
  const newEndTime = new Date(`${newExitDate.value}T${newExitTime.value}:00`)
  const plannedEndTime = new Date(orderDetail.value.planned_end_time)
  const now = new Date()

  // 验证时间
  if (isNaN(newEndTime.getTime())) {
    uni.showToast({
      title: '时间格式不正确',
      icon: 'none'
    })
    return
  }

  if (newEndTime <= plannedEndTime) {
    uni.showToast({
      title: '新离场时间必须晚于预计离场时间',
      icon: 'none'
    })
    return
  }

  if (newEndTime <= now) {
    uni.showToast({
      title: '离场时间不能早于当前时间',
      icon: 'none'
    })
    return
  }

  // 隐藏时间选择器
  hideTimePicker()

  // 确认延后离场
  confirmLateDeparture(newEndTime)
}

// 联系客服（提前离场）
const contactService = () => {
  uni.showModal({
    title: "联系客服",
    content: "请通过平台在线客服申请提前离场退款，我们将按规则计算并处理。",
    showCancel: false,
  })
}

// 超时取消订单提醒联系客服
const contactServiceForOvertime = () => {
  uni.showModal({
    title: "超时取消订单",
    content: "您的订单已超过预计停车时间，取消订单请联系客服处理。",
    showCancel: false,
  })
}
</script>
<style scoped>
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.loading-state {
  padding: 200rpx 40rpx;
  text-align: center;
}

.loading-text {
  color: #999;
  font-size: 28rpx;
}

.error-state {
  padding: 200rpx 40rpx;
  text-align: center;
}

.error-text {
  color: #666;
  font-size: 28rpx;
  margin-bottom: 40rpx;
  display: block;
}

.retry-btn {
  padding: 20rpx 40rpx;
  background-color: #007aff;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.order-detail {
  padding: 20rpx;
}

.status-card {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 40rpx 30rpx;
  margin-bottom: 20rpx;
  text-align: center;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.status-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20rpx;
}

.status-text {
  font-size: 36rpx;
  font-weight: bold;
  padding: 16rpx 32rpx;
  border-radius: 24rpx;
}

.status-pending {
  background-color: #fff3cd;
  color: #856404;
}

.status-progress {
  background-color: #d1ecf1;
  color: #0c5460;
}

.status-completed {
  background-color: #d4edda;
  color: #155724;
}

.status-cancelled {
  background-color: #f8d7da;
  color: #721c24;
}

.order-number {
  font-size: 28rpx;
  color: #666;
}

.overtime-reminder {
  background-color: #fff3cd;
  border: 1rpx solid #ffeaa7;
  border-radius: 8rpx;
  padding: 20rpx;
  margin: 0 20rpx 20rpx;
}

.reminder-text {
  color: #856404;
  font-size: 28rpx;
  line-height: 1.5;
  text-align: center;
  display: block;
}

.info-card {
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.card-header {
  padding: 30rpx 30rpx 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.card-content {
  padding: 20rpx 30rpx 30rpx;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24rpx;
  position: relative;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-label {
  color: #666;
  font-size: 28rpx;
  flex-shrink: 0;
  width: 160rpx;
}

.info-value {
  color: #333;
  font-size: 28rpx;
  flex: 1;
  text-align: right;
  word-break: break-all;
}

.address-text {
  color: #007aff !important;
  cursor: pointer;
}

.copy-tip {
  position: absolute;
  right: 0;
  top: 40rpx;
  font-size: 22rpx;
  color: #999;
}

.phone-text {
  color: #007aff !important;
  cursor: pointer;
  text-decoration: underline;
}

.discount-text {
  color: #ff4757 !important;
}

.total-row {
  border-top: 1rpx solid #f0f0f0;
  padding-top: 24rpx;
  margin-top: 20rpx;
}

.total-price {
  color: #ff4757 !important;
  font-weight: bold;
  font-size: 32rpx !important;
}

.action-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #eee;
  display: flex;
  gap: 20rpx;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.action-btn {
  flex: 1;
  padding: 24rpx 0;
  border-radius: 8rpx;
  font-size: 30rpx;
  font-weight: bold;
  border: 1rpx solid;
}

.cancel-btn {
  background-color: #fff;
  color: #666;
  border-color: #ddd;
}

.pay-btn {
  background-color: #007aff;
  color: #fff;
  border-color: #007aff;
}

.action-btn:active {
  opacity: 0.8;
}

.review-btn {
  background-color: #ff6b35;
  color: #fff;
  border-color: #ff6b35;
}

/* 评价显示样式 */
.review-content {
  padding: 20rpx 0;
}

.review-rating {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.rating-stars {
  display: flex;
  margin-right: 20rpx;
}

.star {
  font-size: 32rpx;
  color: #ddd;
  margin-right: 8rpx;
}

.star-filled {
  color: #ffa500;
}

.rating-text {
  font-size: 28rpx;
  color: #666;
}

.review-comment {
  margin-bottom: 20rpx;
}

.comment-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
}

.review-time {
  margin-bottom: 20rpx;
}

.time-text {
  font-size: 24rpx;
  color: #999;
}

.admin-reply {
  background-color: #f8f9fa;
  border-radius: 8rpx;
  padding: 20rpx;
  margin-top: 20rpx;
}

.reply-item {
  margin-bottom: 16rpx;
}

.reply-item:last-child {
  margin-bottom: 0;
}

.reply-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
}

.reply-author {
  font-size: 24rpx;
  color: #007aff;
  font-weight: bold;
}

.reply-time {
  font-size: 22rpx;
  color: #999;
}

.reply-content {
  font-size: 26rpx;
  color: #333;
  line-height: 1.5;
}

/* 评价对话框样式 */
.review-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.review-dialog {
  background-color: #fff;
  border-radius: 16rpx;
  width: 90%;
  max-width: 600rpx;
  max-height: 80vh;
  overflow: hidden;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.dialog-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  font-size: 40rpx;
  color: #999;
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dialog-content {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.parking-info {
  text-align: center;
  margin-bottom: 40rpx;
}

.parking-name {
  font-size: 30rpx;
  color: #333;
  font-weight: bold;
}

.rating-section {
  margin-bottom: 40rpx;
}

.section-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.rating-stars {
  display: flex;
  justify-content: center;
  margin-bottom: 16rpx;
}

.star.clickable {
  font-size: 48rpx;
  margin: 0 8rpx;
  cursor: pointer;
  transition: all 0.2s;
}

.star.clickable:active {
  transform: scale(1.1);
}

.rating-desc {
  text-align: center;
  font-size: 26rpx;
  color: #666;
  height: 40rpx;
  line-height: 40rpx;
}

.comment-section {
  margin-bottom: 20rpx;
}

.comment-input {
  width: 100%;
  min-height: 120rpx;
  padding: 20rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 28rpx;
  line-height: 1.5;
  margin-bottom: 10rpx;
  box-sizing: border-box;
}

.char-count {
  text-align: right;
  font-size: 24rpx;
  color: #999;
}

.dialog-footer {
  display: flex;
  padding: 20rpx 30rpx 30rpx;
  gap: 20rpx;
}

.dialog-btn {
  flex: 1;
  padding: 24rpx 0;
  border-radius: 8rpx;
  font-size: 28rpx;
  font-weight: bold;
  border: 1rpx solid;
}

.dialog-btn.cancel-btn {
  background-color: #fff;
  color: #666;
  border-color: #ddd;
}

.dialog-btn.submit-btn {
  background-color: #ff6b35;
  color: #fff;
  border-color: #ff6b35;
}

.dialog-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.dialog-btn:active:not(:disabled) {
  opacity: 0.8;
}

/* 停车类型样式 */
.info-value.parking-type {
  font-weight: 500;
}

.info-value.parking-type.indoor {
  color: #1890ff;
}

.info-value.parking-type.outdoor {
  color: #fa8c16;
}

/* 时间选择器模态框样式 */
.time-picker-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.time-picker-dialog {
  background-color: #fff;
  border-radius: 12rpx;
  width: 600rpx;
  max-height: 80vh;
  overflow: hidden;
}

.dialog-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 40rpx;
  border-bottom: 1rpx solid #eee;
}

.dialog-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.close-btn {
  font-size: 40rpx;
  color: #999;
  cursor: pointer;
}

.dialog-content {
  padding: 40rpx;
}

.current-time-info {
  margin-bottom: 30rpx;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
}

.info-text {
  font-size: 28rpx;
  color: #666;
}

.time-selector {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.time-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.time-label {
  font-size: 28rpx;
  color: #333;
  width: 140rpx;
}

.datetime-value {
  flex: 1;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  text-align: center;
  font-size: 28rpx;
  color: #333;
  background-color: #fff;
}

.dialog-footer {
  display: flex;
  border-top: 1rpx solid #eee;
}

.dialog-btn {
  flex: 1;
  padding: 30rpx;
  border: none;
  font-size: 28rpx;
  background-color: transparent;
}

.cancel-btn {
  color: #666;
  border-right: 1rpx solid #eee;
}

.confirm-btn {
  color: #007aff;
  font-weight: 600;
}

.dialog-btn:active {
  opacity: 0.7;
}
</style>
